//
//  AudioPlayer.m
//  LO_MUSIC
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>



static AudioPlayer *audioPlayer = nil;
@interface AudioPlayer ()
//播放器
@property (nonatomic,strong) AVPlayer * localPlayer;

@property (nonatomic,assign,getter=isCurrentIsPlaying) BOOL currentIsPlaying;

@property (nonatomic,strong) NSTimer *timer;

@end
@implementation AudioPlayer
//是否正在播放
-(BOOL)isPlaying{
    return self.isCurrentIsPlaying;
}
//1. 文件是单例
+(instancetype)shareAudioPlayer{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayer = [[AudioPlayer alloc]init];
    });
    return audioPlayer;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        //接收AVPlayer播放完成的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
//接受播放结束的通知
-(void)playEnd{
    //播放结束
    if (self.delegate && [self.delegate respondsToSelector:@selector(playFinish)]) {
        [self.delegate playFinish];
    }
}
//2. 播放
-(void)playWithUrl:(NSString *)url{
    //移除监听状态
    [self.localPlayer.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    //创建一个播放对象
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    //1监听者 2监听的属性 3新值,旧值 4附加信息
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    //播放
    [self.localPlayer replaceCurrentItemWithPlayerItem:item];
    [self play];
//    self.currentIsPlaying = YES;
}
//
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //如果监听的属性不是status,直接返回
    if (![keyPath isEqualToString:@"status"]) {
        return;
    }
    //取出变化的值
    AVPlayerItemStatus value = [change[@"new"] integerValue];
    if (value == AVPlayerItemStatusReadyToPlay) {//准备好了
        [self play];
    }else{//准备失败 准备情况不知道
        
    }
}
//3. 暂停/恢复
-(void)playOrPause{
    if (self.isPlaying) {
        //暂停
        [self pause];
        
    }else {
        
        [self play];
        
    }

}

//播放
-(void)play{
    //播放
    [self.localPlayer play];
    self.currentIsPlaying = YES;
    //repeat YES 每0.1秒执行一次 NO 只执行一次
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

//暂停
-(void)pause{
    
    [self.localPlayer pause];
    self.currentIsPlaying = NO;
    //清空timer
    [self.timer invalidate];
    self.timer = nil;
    
}
//timerAction
-(void)timerAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playWithTime:)]) {
        CGFloat time = self.localPlayer.currentTime.value *1.0 /self.localPlayer.currentTime.timescale;
        [self.delegate playWithTime:time];
    }
    
}

//4. 停止
-(void)stop{
    //把时间设置为0
    [self.localPlayer seekToTime:CMTimeMakeWithSeconds(0, self.localPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {//设置完毕
            [self pause];
        }
    }];
}
//5. 从什么时候开始播放
-(void)seekToWithTime:(CGFloat)time{
    //先暂停
    [self pause];
    //设置从什么地方开始播放
    [self.localPlayer seekToTime:CMTimeMakeWithSeconds(time, self.localPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self play];
        }
    }];
}
//获取音量
-(CGFloat)volume{
    return self.localPlayer.volume;
}
//设置音量
-(void)setVolume:(CGFloat)volume{
    self.localPlayer.volume = volume;
}
//懒加载
- (AVPlayer *)localPlayer{
    
    if (!_localPlayer) {
        _localPlayer = [[AVPlayer alloc]init];
        
        _localPlayer.volume = 0.5;//初始化音量
    }
    
    return _localPlayer;
}

@end
